﻿(function ($) {
    var fs = window.fs = {
        user: {

        },
        sys: {
            defaultDigits: 0,
            siteUrl: "",
            init: function (afterEvent) {

                if (location.pathname.toUpperCase().indexOf("NEWFORM.ASPX") != -1)
                    fs.form.mode = "NEW";
                if (location.pathname.toUpperCase().indexOf("EDITFORM.ASPX") != -1)
                    fs.form.mode = "EDIT";
                if (location.pathname.toUpperCase().indexOf("DISPLAYFORM.ASPX") != -1)
                    fs.form.mode = "DISPLAY";

                var ctx = new SP.ClientContext();
                list = ctx.get_web().get_lists().getById(_spPageContextInfo.pageListId); ;
                ctx.load(list);
                currentUser = ctx.get_web().get_currentUser();
                ctx.load(currentUser);

                ctx.executeQueryAsync(function () {
                    fs.form.title = list.get_title();
                    fs.form.title = fs.form.title ? fs.form.title.replace(/(^|\s+)\w/g, function (s) {
                        return s.toUpperCase();
                    }).replace(/\s+/g, "") : "";

                    fs.form.url = list.get_defaultViewUrl();
                    fs.sys.siteUrl = list.get_parentWebUrl();
                    fs.sys.siteUrl = fs.sys.siteUrl == "/" ? "" : fs.sys.siteUrl;

                    fs.user.loginName = currentUser.get_loginName().split("\\")[1];
                    fs.user.displayName = currentUser.get_title();

                    fs.receiver.getAllCurrency();
                    fs.receiver.getAllEntity();
                    fs.receiver.getAllRGC();
                    afterEvent();
                }, function (e) {
                    //  alert('error');
                });
            }
        },
        form: {
            title: "",
            url: "",
            mode: "",
            isBudget: function () {
                return this.title.indexOf("Budget_") != -1;
            },
            isForecast: function () {
                return this.title.indexOf("Forecast_") != -1;
            },
            isActual: function () {
                return this.title.indexOf("Actual_") != -1;
            },
            allEntity: [],
            allRGC: [],
            allCurrency: [],
            allGrayField: []
        },
        insert: {},
        calc: {
            version: 1.0
        },
        receiver: {
            fsMonthSelectorReceiver: {
                handler: [],
                exec: function (callback) {
                    for (var i = 0; i < this.handler.length; i++) {
                        var a = this.handler[i];
                        a.handler(a.args);
                    }
                },
                push: function (fun, args) {
                    this.handler.push({ handler: fun, args: args });
                }
            },
            getSubEntityByAccountCode: function (pars, callback) {
                //get sub AIA data from SUBAIA Table by AccountCode field
                //return DataType Array
                // 
                var args = String.format(" (AccountCode eq '{0}') and (Year eq {1}) and (Month eq {2} or Month eq {3}) and (CompanyCode eq '{4}')",
        pars.accountcode, pars.year, pars.month - 1, pars.month, fs.form.companycode);

                for (var i = 0; i < fs.util.cache.length; i++) {
                    var cacheItem = fs.util.cache[i];
                    if (cacheItem.source == pars.list && cacheItem.accountcode == pars.accountcode && cacheItem.year == pars.year && cacheItem.companycode == fs.form.companycode && (cacheItem.month == pars.month || cacheItem.month == pars.month - 1)) {
                        callback(cacheItem.data);
                        return;
                        break;
                    }
                }

                var url = String.format(fs.sys.siteUrl + "/_vti_bin/ListData.svc/{0}?$filter={1}", pars.list, args) + "&timemark=" + new Date().getTime();
                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: "json",
                    async: false,
                    success: function (d) {
                        var cacheItem = {
                            source: pars.list,
                            accountcode: pars.accountcode,
                            companycode: fs.form.companycode,
                            year: pars.year,
                            month: pars.month,
                            data: d
                        };
                        // if (d.d.results.length > 0)
                        fs.util.cache.push(cacheItem);

                        callback(cacheItem.data);
                    },
                    error: function (e) { }
                });

            },
            commonReceiver: function (title, callback) {
                var url = String.format(fs.sys.siteUrl + "/_vti_bin/ListData.svc/" + title);
                $.ajax({
                    url: url,
                    type: "GET",
                    dataType: "json",
                    async: false,
                    success: function (d) {
                        callback(d.d.results)
                    },
                    error: function (e) { }
                });
            },
            getAllCurrency: function () {
                this.commonReceiver("Currency", function (d) {
                    $(d).each(function () {
                        fs.form.allCurrency.push({
                            text: this.Currency,
                            value: this.Currency
                        });
                    });
                });
            },
            getAllEntity: function () {
                this.commonReceiver("Entity", function (d) {
                    $(d).each(function () {
                        fs.form.allEntity.push({
                            text: this.CompanyName,
                            value: this.CompanyCode
                        });
                    });
                });
            },
            getAllRGC: function () {
                this.commonReceiver("RGC", function (d) {
                    $(d).each(function () {
                        fs.form.allRGC.push({
                            RGC: this.RGC,
                            Description: this.Description,
                            Category: this.CategoryValue
                        });
                    });
                });
            }
        },
        ui: {
            //遮罩层，一个Loading层，用于提示正在加载
            mask: function (obj, info, callback) {
                fs.ui.clear(obj);
                if (typeof info == 'undefined') info = "正在处理中...";
                var maskhtml = '<div class="masklayer"></div>';
                var loadinghtml = '<div id="loading" class="border"><img src="/_layouts/images/loading.gif" alt=" " /> ' + info + '</div>';
                var self = $(obj);

                var w = self.get(0).scrollWidth;
                var h = self.get(0).scrollHeight;

                self.onscroll = function () { return false; }
                //self.css('overflow', 'hidden');

                var loadingWidth = 80; //  $(loadinghtml).scrollWidth();
                var loadingHeight = 20; // $(loadinghtml).scrollHeight();

                self.css("position", "relative").append($(maskhtml).css({ width: w + "px", height: h + "px", "line-height": h + "px" }));
                self.append($(loadinghtml).css({
                    left: ((self.outerWidth() / 2 + self.get(0).scrollLeft) - (loadingWidth / 2) + "px"),
                    top: ((self.outerHeight() / 2 + self.get(0).scrollTop) - (loadingHeight / 2) + "px")
                }));
                if (typeof callback != 'undefined') {
                    setTimeout(callback, 100);
                    //callback(); 
                }
                //$('#loading').focus();
                // document.onkeydown = function (e) { return false; }
            },
            //取消遮罩层
            clear: function (obj) {
                var self = $(obj);
                self.onscroll = function () { return true; }
                self.find('div.masklayer,div#loading').remove();
                //self.css('overflow', 'auto');
            }

        },
        util: {
            autoAppendProfixToReceive: true,
            receiveControlValue: function () {
                var controlValue = $("[id$=ControlValue]").val();
                if (!controlValue) return;
                var allControlField = JSON.parse(controlValue);

                $("[control=true]").each(function (i) {
                    $(this).find("div.fs-control-display").text(allControlField[i]);
                });
            },
            saveControlValue: function () {
                var allControlField = [];
                $("[control=true]").each(function (i) {
                    var controlValue = $(this).find("div.fs-control-display").text();
                    allControlField.push(controlValue);
                });
                $("[id$=ControlValue]").val(JSON.stringify(allControlField));
            },
            extend: function (destination, source) {
                var getType = function (o) {
                    var _t;
                    return ((_t = typeof (o)) == "object" ? o == null && "null" || Object.prototype.toString.call(o).slice(8, -1) : _t).toLowerCase();
                }
                for (var p in source) {
                    if (getType(source[p]) == "array" || getType(source[p]) == "object") {
                        destination[p] = getType(source[p]) == "array" ? [] : {};
                        arguments.callee(destination[p], source[p]);
                    }
                    else {
                        destination[p] = source[p];
                    }
                }
            },
            combine: function (objectArr) {
                var itemTemplate = objectArr[0]; ;
                //累加Loading File中的相同月份值
                if (objectArr.length > 1) {

                    for (var i = 1; i < objectArr.length; i++) {
                        var currentItem = objectArr[i];
                        for (var field in itemTemplate) {
                            var fieldValue = itemTemplate[field];
                            fieldValue = fieldValue == null ? 0 : fieldValue;
                            var cfieldValue = currentItem[field];
                            cfieldValue = cfieldValue == null ? 0 : cfieldValue;

                            if ((parseFloat(fieldValue) || parseFloat(fieldValue) == 0) && (parseFloat(cfieldValue) || parseFloat(cfieldValue) == 0)) {
                                fieldValue = parseFloat(fieldValue);
                                cfieldValue = parseFloat(cfieldValue);
                                itemTemplate[field] = fieldValue + cfieldValue;
                            }
                        }
                    }

                    objectArr = [itemTemplate];
                }

                return itemTemplate
            },
            getLastDay: function (year, month) {

                var new_year = year ? year : fs.form.year;    //取当前的年份        
                var new_month = month ? month : fs.form.month; //取下一个月的第一天，方便计算（最后一天不固定）

                if (month > 12)            //如果当前大于12月，则年份转到下一年        
                {
                    new_month -= 12;        //月份减        
                    new_year++;            //年份增        
                }
                var new_date = new Date(new_year, new_month, 1);                //取当年当月中的第一天        
                return (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate(); //获取当月最后一天日期        
            },
            toFix: function (value, digits) { //important change 2014-12-28 from mike
                value = fs.util.strFilter(value);
                if (!isNaN(value) && parseFloat(value)) {
                    return parseFloat(value).toFix(digits);
                }
                return value ? value : 0.00;
            },
            strFilter: function (str) {
                if (typeof str != 'undefined' && str != null) {
                    str = str.toString().replace(/_CM_/g, fs.form.month);
                    str = str.toString().replace(/_M_/g, fs.form.month);
                    return str.replace(/,/g, "");
                }
                return str;
            },
            eval: function (equ) {
                try {
                    equ = fs.util.strFilter(equ);
                    var fs_v = eval(equ);
                    fs_v = fs_v == 'Infinity' || fs_v == '-Infinity' ? 0 : fs_v;
                    return isNaN(fs_v) ? 0 : fs_v;
                } catch (e) {
                    fs.util.log(JSON.stringify(e));
                }
            },
            log: function (msg) {

                try {
                    console.log(msg);
                } catch (e) {
                    // alert(JSON.stringify(e));
                }
            },
            loadingFile: {
                handler: [],
                get: function (v) {
                    for (var i = 0; i < this.handler.length; i++) {
                        var value = fs.util.ref(this.handler[i], v, "");
                        if (value)
                            return value;
                    }
                },
                set: function (fun) {
                    this.handler.push(fun);
                }
            },
            cache: [],
            pageLoadFunction: {
                handler: [],
                exec: function (callback) {

                    try {
                        fs.ui.mask("#s4-workspace", "processing...", function () {
                            var sortArray = fs.util.pageLoadFunction.handler.sort(by("index"));
                            for (var i = 0; i < sortArray.length; i++) {
                                var a = fs.util.pageLoadFunction.handler[i];
                                a.handler(a.args);
                            }
                            callback();

                            fs.ui.clear("#s4-workspace");
                        });
                    } catch (e) {
                        fs.ui.clear("#s4-workspace");
                    }
                },
                push: function (fun, args, index) {
                    this.handler.push({ handler: fun, args: args, index: index });
                }
            },
            beforeSubmitFunction: {
                handler: [],
                exec: function (button) {
                    if (window._fsSubmitingID == button.id) { alert('Processing Please wait .'); return false; }

                    for (var i = 0; i < this.handler.length; i++) {
                        var a = this.handler[i];
                        a.handler(a.args);
                    }
                    window._fsSubmitingID = button.id;
                    return true;
                },
                push: function (fun, args) {
                    this.handler.push({ handler: fun, args: args });
                }
            },
            getBudgetItemYTDMValue: function (row, m) {
                var month = parseInt(m) ? m : fs.form.month;
                var tmp = 0;
                for (var i = 1; i <= month; i++) {
                    var field = fs.util.getMonthByNumber(i);
                    tmp += parseFloat(fs.util.ref(row, field));
                }
                return tmp;
            },
            getMonthByNumber: function (num) {
                num = parseInt(num);
                var tab = [{ index: 1, text: "Jan", edit: true, width: 80, rowText: "Jan" },
              { index: 2, text: "Feb", edit: true, width: 80, rowText: "Feb" },
              { index: 3, text: "Mar", edit: true, width: 80, rowText: "Mar" },
              { index: 4, text: "Apr", edit: true, width: 80, rowText: "Apr" },
              { index: 5, text: "May", edit: true, width: 80, rowText: "May" },
              { index: 6, text: "Jun", edit: true, width: 80, rowText: "Jun" },
              { index: 7, text: "Jul", edit: true, width: 80, rowText: "Jul" },
              { index: 8, text: "Aug", edit: true, width: 80, rowText: "Aug" },
              { index: 9, text: "Sep", edit: true, width: 80, rowText: "Sep" },
              { index: 10, text: "Oct", edit: true, width: 80, rowText: "Oct" },
              { index: 11, text: "Nov", edit: true, width: 80, rowText: "Nov" },
              { index: 12, text: "Dec", edit: true, width: 80, rowText: "Dec"}];
                var temp = '';

                tab.forEach(function (f) {
                    if (f.index == num)
                        temp = f.text;
                    return;
                });
                return temp;
            },
            setValue: function (control, v, digits) {
                try {
                    var input;
                    var numberVar = parseFloat(v);

                    digits = digits ? digits : control.attr('digits'); //首先取传入参数，后取绑定参数
                    digits = digits ? digits : fs.sys.defaultDigits; //其次取默认参数

                    if (!numberVar && v.toString().trim() == "")
                        numberVar = 0;

                    if (numberVar && typeof numberVar == "number")
                        numberVar = numberVar.toFix(digits);
                    else
                        numberVar = v;


                    if (!control.is("input")) {
                        input = control.find("input[type=text]");
                        if (input.length > 0) {
                            var oldvalue = input.val();

                            if (!isNaN(parseFloat(fs.util.strFilter(oldvalue))) || oldvalue.trim() == "")
                                input.val(numberVar);
                        }
                        else
                            control.text(numberVar);
                    }
                    else {
                        control.val(numberVar);
                    }
                } catch (e) {
                    fs.util.log("fs.lib.js line:306;function:setValue ========" + JSON.stringify(e));
                }
            },
            getValue: function (control) {
                var input, v = 0.00;

                if (!control.is("input")) {
                    input = control.find("input[type=text]");
                    if (input.length > 0)
                        v = input.val();
                    else {
                        input = control.find("span.hide-input");
                        if (input.length > 0)
                            v = input.text();
                        else
                            v = control.text();
                    }
                }
                else {
                    v = control.val();
                }

                return v ? v : 0.00;
            },
            beforeSubmit: function () {
                $(fs.util.beforeSubmitFunction).each(function () {
                    this();
                });
                return true;
            },
            ref: function (obj, fieldName, defaultValue) {
                defaultValue = (typeof defaultValue != 'undefined') ? defaultValue : 0.00;

                for (i in obj) {
                    if (i.toUpperCase() == fieldName.toUpperCase())
                        return fs.util.strFilter(obj[i]);
                }
                return defaultValue;
            },
            getNumberFromObjectAndFix: function (obj, fieldName, defaultValue, digits) {
                var value = fs.util.ref(obj, fieldName, defaultValue);
                return fs.util.toFix(value, digits);
            },
            search: function (obj, fieldName, fieldValue) {
                var temp = new Array();
                if (typeof fieldValue == 'undefined')
                    return temp;

                for (var i = 0; i < obj.length; i++) {
                    var value = obj[i][fieldName];
                    if (typeof value == "number") {
                        if (value == fieldValue)
                            temp.push(obj[i]);
                    }
                    if (typeof value == "string") {
                        if (value.toUpperCase() == fieldValue.toUpperCase())
                            temp.push(obj[i]);
                    }
                }
                return temp;
            }
        }

    }


    /*
    fs.user = function (user) {
    user = fs.sys.userinit();
    alert(user.username);
    } (fc.user || {});

    */

    window['fs'] = fs;
})($);
_spBodyOnLoadFunctionNames.push("fs");


function GetHtmlTableJson(TableIds) {
    var HtmlTableJson = "";
    for (var i = 0; i < TableIds.length; i++) {
        //去处a标签行和control行
        $(TableIds[i] + " tr[control=true]").remove();
        HtmlTableJson += GetTrJson($( TableIds[i]));
    }
    return HtmlTableJson;
}

//获得tr的json集合
function GetTrJson(oTd) {
    var htmljson = "";
    $(oTd).each(function () {
        var HtmlTableJson = "[";
        var RowIndex = 0;
        var StartCellIndex = 0;
        var MergeRowCount = 0;

        var readData = function (obj) {
            if ($(obj).find("input[type=text]").length == 0) {
                return $(obj).text().toString();
            }
            else {
                return $($(obj).find("input[type=text]")[0]).val().toString();
            }
        }

        //层级处理
//        if ($(this).children("table").length > 0) {
//            oTd = $(this).children("table");
//        }
//        if ($(this).children("thead").length > 0 && $(this).children("tbody").length > 0) {
//            oTd = $(this).children("thead,tbody");
//        }
//        if ($(this).children("thead").length > 0) {
//            oTd = $(this).children("thead");
//        }
//        if ($(this).children("tbody").length > 0) {
//            oTd = $(this).children("tbody");
//        }
//        else
            oTd = $(this);

        $(oTd).find("tr").each(function () {
            var Table_Tr = "";
            Table_Tr += "{";
            Table_Tr += "\"RowClass\":\"\",";
            Table_Tr += "\"RowIndex\":" + RowIndex + ","; //行索引
            Table_Tr += "\"CellS\":[";

            var CellIndex = 0;

            //采用合并单元格的索引
            if (StartCellIndex > 0) {
                CellIndex = StartCellIndex;
            }

            var Table_Td = "";
            $(this).children("td,th").each(function () {
                Table_Td += "{";

                //索引
                Table_Td += "\"CellIndex\":" + CellIndex + ",";

                //内容
                if ($(this).find("tr").length > 0) {
                    Table_Td += "\"Content\":\"\",";
                }
                else if ($(this).find("select").length > 0) {
                    Table_Td += "\"Content\":\"" + $.trim($(this).find("select").find("option:selected").text()) + "\",";
                }
                else {
                    Table_Td += "\"Content\":\"" + $.trim(readData(this)) + "\",";
                }
                //宽
                if ($(this).attr("colspan") != undefined && $(this).attr("colspan") != "") {
                    Table_Td += "\"CellWidth\":" + $(this).attr("colspan") + ",";
                }
                else {
                    Table_Td += "\"CellWidth\":1,";
                }
                //方向
                if ($(this).attr("align") != undefined && $(this).attr("align") != "")
                    Table_Td += "\"CellAlign\":\"" + $(this).attr("align") + "\",";
                else
                    Table_Td += "\"CellAlign\":\"\",";
                //高
                if ($(this).attr("rowspan") != undefined && $(this).attr("rowspan") != "") {
                    Table_Td += "\"CellHeight\":" + $(this).attr("rowspan") + ",";
                    MergeRowCount = parseInt($(this).attr("rowspan"));  //仅限于一行中只有一个rowspan
                    //StartCellIndex = parseInt($(this).attr("colspan")) - 1;
                    StartCellIndex = 1; //暂时只支持第一列合并行
                }
                else {
                    Table_Td += "\"CellHeight\":1,";
                }
                //内部集合
                if ($(this).find("tr").length > 0) {
                    Table_Td += "\"RowS\":[";
                    Table_Td += GetTrJson($(this)); //**********递归获取
                    Table_Td += "]";
                }
                else {
                    Table_Td += "\"RowS\":null";
                }
                Table_Td += "},";
                CellIndex += 1;
            });
            if (Table_Td.length > 0) {
                Table_Tr += Table_Td.substr(0, Table_Td.length - 1);
            }

            Table_Tr += "]";
            Table_Tr += "},";
            HtmlTableJson += Table_Tr;
            RowIndex += 1;

            //处理合并行结构
            if (MergeRowCount > 0) {
                MergeRowCount -= 1;
                if (MergeRowCount == 0) {
                    StartCellIndex = 0;
                }
            }
        });
        if (HtmlTableJson.length > 0) {
            HtmlTableJson = HtmlTableJson.substr(0, HtmlTableJson.length - 1);
        }
        HtmlTableJson += "]";
        HtmlTableJson += "ゥ";
        htmljson += HtmlTableJson;
    })
    return htmljson;
}

function getFile(tid) {
    var oTd = $("#" + tid);
    if ($(oTd).children("tbody").length > 0) {
        oTd = $(oTd).children("tbody");
    }
    var obj = {};
    $(oTd).children("tr").each(function () {
        var th = $(this).children("th");
        var td = $(this).children("td");
        for (var i = 0; i < th.length; i++) {
            var key = th[i].innerText.replace(/\s+/g, "").replace(":", "");
            var vals;
            if ($(td[i]).find("input[type=text]").length > 0)
                vals = $(td[i]).find("input[type=text]").val().replace(/\s+/g, "").replace(":", "");
            else
                vals = $(td[i]).text().replace(/\s+/g, "").replace(":", "");
            obj[key] = vals;
        }
    })
    return obj;
}

/*------------------------------mike new----------------------------------------------

var dataToPost={ fileName:"",sheets:[] }
dataToPost.sheets.push(
{
name:"sheet1",
columnWidth:[10,23,44,33,55,66,33,332],
rows:[
{
index:0,
headRow:true,
rowStyle:"",
columns:[]
}
]
}
)
*/
var _fsReportHeaderIdentity = ".fs-common-selector";
var _fsReportMainTableIdentity = ".commontable";
function getSheetHeader() {
    var sheetHeaderRows = getRowInstance($(_fsReportHeaderIdentity));
    $(sheetHeaderRows).each(function () { this.rowStyle = 1; this.headRow = true; });
    //set two empty row
    sheetHeaderRows.push({ emptyRow: true });
    sheetHeaderRows.push({ emptyRow: true });
    return sheetHeaderRows;
}
function getSheetInstance(table) {
    var sheet = {};
    sheet.name = getAttrOrDefault(table, "name", "");
    sheet.columnWidth = getColumnWidth(table);
    sheet.rows = getSheetHeader();
    var mainRows = getRowInstance(table)
    sheet.rows = sheet.rows.concat(mainRows);
    return sheet;
}

function getRowInstance(table) {
    var rows = [];
    var rowindex = 0;
    table.find("tr").each(function () {
        var cellindex = 0;
        var rowobj = {};
        var columns = [];
        rowobj.index = rowindex;

        if ($(this).parent("thead").length > 0 || $(this).attr("thead") == 'true') {
            rowobj.rowStyle = 2;
            rowobj.titleRow = true;
        }

        $(this).children("td,th").each(function () {
            var celldata = new Object();
            celldata.CellIndex = cellindex;
            celldata.Content = getinputval($(this));

            var width = $(this).attr("colspan");
            if (width != null && width > 1) {
                celldata.CellWidth = width;
                //  cellindex += (width - 1);
            }

            var height = $(this).attr("rowspan");
            if (height != null && height > 1)
                celldata.CellHeight = height

            columns.push(celldata);
            cellindex++;
        });
        rowobj.columns = columns;
        rows.push(rowobj);
        rowindex++;
    })

    return rows;
}

function getColumnWidth(table) {
    var widths = [];
    var alltr = table.find("tr");
    var itemCount = alltr.length;
    for (var i = 0; i < itemCount; i++) {
        var tr = $(alltr[i]);
        var hascolpspan = tr.find("td[colspan]").length > 0 && tr.find("td[colspan!=1]").length > 0;

        if (!hascolpspan) {
            tr.find("td").each(function () {
                widths.push($(this).width());
            })
            return widths;
        }
    }
    return widths;
}

function getAttrOrDefault(obj, name, def) {
    var tmp = obj.attr(name);
    return tmp || def;
}

function GetTableJson(tableids) {
    var objdata = [];
    var tabindex = 0;
    for (var i = 0; i < tableids.length; i++) {
        var table = tableids[i];
        $(table).each(function () {
            var rowindex = 0;
            var obj = {};
            var data = [];
            $(this).find("tr").each(function () {
                var cellindex = 0;
                var rowobj = {};
                var rowdata = [];
                rowobj.RowIndex = rowindex;
                if (i == 0)
                    rowobj.RowClass = "thead";
                else {
                    if ($(this).parent("thead").length > 0)
                        rowobj.RowClass = "thead";
                    else
                        rowobj.RowClass = $(this).attr("class");
                }
                $(this).children("td,th").each(function () {
                    var celldata = new Object();
                    celldata.CellIndex = cellindex;
                    celldata.Content = getinputval($(this));
                    celldata.CellWidth = $(this).attr("colspan") == "" ? "1" : $(this).attr("colspan");
                    celldata.CellHeight = $(this).attr("rowspan") == "" ? "1" : $(this).attr("rowspan");
                    rowdata.push(celldata);
                    cellindex += 1;
                });
                rowobj.rowdata = rowdata;
                data.push(rowobj);
                rowindex += 1;
            })
            obj.title = "table" + tabindex;
            obj.datas = data;
            objdata.push(obj);
            tabindex += 1;
        })
    }
    var json = JSON.stringify(objdata);
    return json;
}

function getinputval(obj) { 
    if ($(obj).find("select").length > 0) {
        return $.trim($(obj).find("select").find("option:selected").text())
    }
    else if ($(obj).find("input[type=text]").length == 0) {
        return $(obj).text();
    }
    else {
        return $(obj).find("input[type=text]").val();
    }
}
